package com.blogs.web.controller.admin;

import com.blogs.common.constant.WebConst;
import com.blogs.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hubiao
 */
@Api("登录相关接口")
@Slf4j
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {

    @ApiOperation("跳转登录页")
    @GetMapping(value = "/login")
    public String login() {
        return "admin/login";
    }


    /**
     * 登录异常返回信息
     *
     * @param request
     * @param response
     */
    @RequestMapping("/login/error")
    public void loginError(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType( "text/html;charset=utf-8" );
        AuthenticationException exception =
                (AuthenticationException) request.getSession().getAttribute( "SPRING_SECURITY_LAST_EXCEPTION" );
        try {
            response.getWriter().write( exception.toString() );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/logout")
    public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        // 移除session
        session.removeAttribute( WebConst.LOGIN_SESSION_KEY );
        // 设置cookie值和时间为空
        Cookie cookie = new Cookie( WebConst.USER_IN_COOKIE, "" );
        cookie.setValue( null );
        cookie.setMaxAge( 0 );
        cookie.setPath( "/" );
        response.addCookie( cookie );
        try {
            // 跳转到登录页面
            response.sendRedirect( "/admin/login" );
        } catch (IOException e) {
            e.printStackTrace();
            log.error( "注销失败", e );
        }
    }


}
